/**
 * 云书签主应用 - 重构版
 * 使用模块化架构，提高可维护性
 */

class NavigationManager {
    constructor() {
        // 初始化服务和管理器
        this.api = apiService;
        this.uiManager = new UIManager();
        this.categoryManager = new CategoryManager(this.api);
        this.bookmarkManager = new BookmarkManager(this.api);
        
        // 状态
        this.currentUser = null;
        this.isLoggedIn = false;
        
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        console.log('应用初始化...');
        
        // 检查登录状态
        await this.checkAuthenticationSilent();
        
        // 初始化UI
        this.uiManager.setLoginState(this.isLoggedIn, this.currentUser);
        this.uiManager.renderRecommendedTools();
        this.uiManager.renderMonthlyRankings();
        this.uiManager.initializeCategoryTabs();
        
        // 绑定事件
        this.initializeEventListeners();
        
        // 如果已登录，加载用户数据
        if (this.isLoggedIn) {
            await this.loadUserData();
            this.generateSmartRecommendations();
        }
        
        console.log('应用初始化完成');
    }

    /**
     * 静默检查认证状态
     */
    async checkAuthenticationSilent() {
        const token = localStorage.getItem('auth_token');
        const expires = localStorage.getItem('auth_expires');
        
        if (!token || !expires) {
            this.isLoggedIn = false;
            return false;
        }
        
        const expiresDate = new Date(expires);
        if (expiresDate <= new Date()) {
            this.clearAuthData();
            this.isLoggedIn = false;
            return false;
        }
        
        try {
            const response = await this.api.verifyToken();
            if (response.success && response.data.valid) {
                this.currentUser = response.data.user;
                this.isLoggedIn = true;
                return true;
            } else {
                this.clearAuthData();
                this.isLoggedIn = false;
                return false;
            }
        } catch (error) {
            this.clearAuthData();
            this.isLoggedIn = false;
            return false;
        }
    }

    /**
     * 加载用户数据
     */
    async loadUserData() {
        await Promise.all([
            this.categoryManager.loadCategories(),
            this.bookmarkManager.loadBookmarks()
        ]);
        
        // 确保默认分组存在
        await this.categoryManager.ensureDefaultCategory();
        
        this.categoryManager.renderCategorySelects();
        this.categoryManager.renderCategoriesBar();
        this.bookmarkManager.renderBookmarks();
        this.bookmarkManager.updateStats();
    }

    /**
     * 初始化事件监听
     */
    initializeEventListeners() {
        // UI管理器事件
        this.uiManager.initializeEventListeners();
        
        // 如果已登录，绑定收藏相关事件
        if (this.isLoggedIn) {
            this.initializeBookmarkEvents();
            this.initializeCategoryEvents();
        }
        
        // 监听未授权事件
        window.addEventListener('unauthorized', () => {
            this.handleUnauthorized();
        });
        
        // 监听分组更新事件
        window.addEventListener('categoriesUpdated', async () => {
            await this.categoryManager.loadCategories();
            this.categoryManager.renderCategorySelects();
            this.categoryManager.renderCategoriesBar();
        });
        
        // 监听分组筛选变化
        window.addEventListener('categoryFilterChange', (e) => {
            const categoryId = e.detail.categoryId.toString();
            this.bookmarkManager.filterByCategory(categoryId);
            this.bookmarkManager.renderBookmarks();
            this.categoryManager.renderCategoriesBar(categoryId);
        });
        
        // 监听收藏移动/删除事件
        window.addEventListener('bookmarkMoved', async () => {
            await this.categoryManager.loadCategories();
            await this.bookmarkManager.loadBookmarks();
            this.categoryManager.renderCategorySelects();
            this.categoryManager.renderCategoriesBar();
            this.bookmarkManager.renderBookmarks();
        });
        
        window.addEventListener('bookmarkDeleted', async () => {
            await this.categoryManager.loadCategories();
            this.categoryManager.renderCategorySelects();
            this.categoryManager.renderCategoriesBar();
        });
    }

    /**
     * 初始化收藏相关事件
     */
    initializeBookmarkEvents() {
        // 添加收藏按钮
        const addBookmarkBtn = document.getElementById('addBookmark');
        if (addBookmarkBtn) {
            addBookmarkBtn.addEventListener('click', () => this.addBookmark());
        }

        // 回车键添加收藏
        const websiteName = document.getElementById('websiteName');
        const websiteUrl = document.getElementById('websiteUrl');
        
        if (websiteName) {
            websiteName.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') this.addBookmark();
            });
        }
        
        if (websiteUrl) {
            websiteUrl.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') this.addBookmark();
            });
        }

        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('input', debounce((e) => {
                this.bookmarkManager.searchBookmarks(e.target.value);
                this.bookmarkManager.renderBookmarks();
            }, 300));
        }

        // 分组筛选
        const categoryFilter = document.getElementById('categoryFilter');
        if (categoryFilter) {
            categoryFilter.addEventListener('change', (e) => {
                window.dispatchEvent(new CustomEvent('categoryFilterChange', { 
                    detail: { categoryId: e.target.value } 
                }));
            });
        }
    }

    /**
     * 初始化分组相关事件
     */
    initializeCategoryEvents() {
        const manageCategoriesBtn = document.getElementById('manageCategoriesBtn');
        if (manageCategoriesBtn) {
            manageCategoriesBtn.addEventListener('click', () => {
                this.categoryManager.showManagementDialog();
            });
        }
    }

    /**
     * 添加收藏
     */
    async addBookmark() {
        const nameInput = document.getElementById('websiteName');
        const urlInput = document.getElementById('websiteUrl');
        const categorySelect = document.getElementById('categorySelect');
        
        if (!nameInput || !urlInput || !categorySelect) return;
        
        const name = nameInput.value.trim();
        const url = urlInput.value.trim();
        let categoryId = categorySelect.value || null;

        // 如果没有选择分组，自动使用默认分组
        if (!categoryId) {
            await this.categoryManager.ensureDefaultCategory();
            categoryId = this.categoryManager.getDefaultCategoryId();
        }

        const bookmark = await this.bookmarkManager.addBookmark(name, url, categoryId);
        if (bookmark) {
            // 清空输入框
            nameInput.value = '';
            urlInput.value = '';
            categorySelect.value = '';

            // 刷新显示
            await this.categoryManager.loadCategories();
            this.categoryManager.renderCategorySelects();
            this.categoryManager.renderCategoriesBar();
            this.bookmarkManager.renderBookmarks();
            this.bookmarkManager.updateStats();
        }
    }

    /**
     * 生成智能推荐
     */
    generateSmartRecommendations() {
        if (!this.isLoggedIn || !this.bookmarkManager.bookmarks || 
            this.bookmarkManager.bookmarks.length === 0) {
            return;
        }

        // 分析用户兴趣
        const interests = this.bookmarkManager.analyzeUserInterests();
        const recommendations = this.getRecommendationsByInterests(interests);
        
        if (recommendations.length > 0) {
            this.uiManager.renderSmartRecommendations(recommendations);
        }
    }

    /**
     * 根据兴趣获取推荐
     */
    getRecommendationsByInterests(interests) {
        const recommendations = [];
        const maxInterest = Math.max(...Object.values(interests));
        
        if (maxInterest === 0) return [];

        if (interests.efficiency === maxInterest) {
            recommendations.push(...recommendedTools.efficiencyTools.slice(0, 3));
        }
        if (interests.learning === maxInterest) {
            recommendations.push(...recommendedTools.learningResources.slice(0, 3));
        }
        if (interests.development === maxInterest) {
            recommendations.push(...recommendedTools.devTools.slice(0, 3));
        }
        if (interests.design === maxInterest) {
            recommendations.push(...recommendedTools.designTools.slice(0, 3));
        }

        // 去重并限制数量
        return recommendations
            .filter((tool, index, arr) => arr.findIndex(t => t.name === tool.name) === index)
            .slice(0, 6);
    }

    /**
     * 处理未授权
     */
    handleUnauthorized() {
        this.clearAuthData();
        this.isLoggedIn = false;
        this.currentUser = null;
        this.uiManager.setLoginState(false);
        showNotification('登录已过期，请重新登录', 'warning');
    }

    /**
     * 清除认证数据
     */
    clearAuthData() {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_expires');
        localStorage.removeItem('remember_me');
        localStorage.removeItem('user_info');
    }

    /**
     * 退出登录
     */
    async logout() {
        try {
            await this.api.logout();
        } catch (error) {
            // 忽略错误，继续执行退出流程
        }
        
        this.clearAuthData();
        this.isLoggedIn = false;
        this.currentUser = null;
        this.bookmarkManager.bookmarks = [];
        this.categoryManager.categories = [];
        
        document.title = '云书签';
        this.uiManager.setLoginState(false);
        showNotification('已退出登录', 'info');
    }
}

// ==================== 全局辅助函数 ====================

/**
 * 打开网站
 */
function openWebsite(url) {
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        url = 'https://' + url;
    }
    window.open(url, '_blank');
}

/**
 * 显示登录页面
 */
function showLogin() {
    window.location.href = 'auth.html';
}

/**
 * 显示注册页面
 */
function showRegister() {
    window.location.href = 'auth.html#register';
}

/**
 * 切换用户下拉菜单
 */
function toggleUserDropdown() {
    if (navigationManager && navigationManager.uiManager) {
        navigationManager.uiManager.toggleUserDropdown();
    }
}

/**
 * 显示个人收藏
 */
function showPersonalBookmarks() {
    if (navigationManager && navigationManager.uiManager) {
        navigationManager.uiManager.showPersonalBookmarks();
    }
}

/**
 * 显示推荐导航
 */
function showRecommendedNavigation() {
    if (navigationManager && navigationManager.uiManager) {
        navigationManager.uiManager.showRecommendedNavigation();
    }
}

/**
 * 显示个人资料页面
 */
function showProfile() {
    window.location.href = 'profile.html';
}

/**
 * 退出登录
 */
function logout() {
    if (navigationManager) {
        navigationManager.logout();
    }
}

// ==================== 应用初始化 ====================

let navigationManager;
let bookmarkManager;
let categoryManager;

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，初始化应用...');
    
    // 创建主应用实例
    navigationManager = new NavigationManager();
    
    // 导出管理器供全局使用（用于onclick等）
    bookmarkManager = navigationManager.bookmarkManager;
    categoryManager = navigationManager.categoryManager;
    
    // 同时设置到window对象（确保在任何地方都能访问）
    window.bookmarkManager = bookmarkManager;
    window.categoryManager = categoryManager;
    window.navigationManager = navigationManager;
    
    console.log('应用启动完成！');
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

